package com.youpingou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youpingou.domain.Address;
import com.youpingou.domain.Category;
import com.youpingou.mapper.AddressMapper;
import com.youpingou.mapper.CategoryMapper;
import com.youpingou.service.AddressService;
import com.youpingou.service.CategoryService;
import com.youpingou.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Service
@Transactional
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    public List<Address> findAddressByUserId(HttpServletRequest request) {
        //1 获取token
        String token = request.getHeader("authorization");
        //2 解析token
        Claims claims = JWTUtil.parseToken(token, "admin");
        //3 返回UserId
        String userId = claims.get("userId").toString();

        //4 查找结果
        return addressMapper.findAddressByUserId(Integer.parseInt(userId));
    }

    public Address findAddressByAddressId(Integer addressId) {
        return addressMapper.selectById(addressId);
    }

    @Override
    public Integer addAddress(Address address,HttpServletRequest request) {
        //1 获取token
        String token = request.getHeader("authorization");
        //2 解析token
        Claims claims = JWTUtil.parseToken(token, "admin");
        //3 返回UserId
        String userId = claims.get("userId").toString();
        address.setUserId(Integer.parseInt(userId));

        baseMapper.insert(address);
        return address.getId();
    }

    @Override
    public Integer updateAddress(Address address) {
        return baseMapper.updateById(address);
    }

}